import store from "@/store"

function HTTP(obj, config) {

	let defaultConfig = {
		isRes: false,
		loading: false
	}

	config = {
		...defaultConfig,
		...config
	}


	// 如果需要显示loading,mask防止点击穿透
	config.loading && uni.showLoading({
		title: '加载中',
		mask: true
	});

	return new Promise((resolve, reject) => {

		let options = {
			url: "",
			method: "",
			data: {},
			dataType: "json",
			header: {
				"content-type": "application/json",
				"X-requested-With": "XMLHttpRequest",
				"Authorization": "Bearer " + uni.getStorageSync("token") || ""
			},
			success: (res) => {
				// console.log("HTTP请求结果：",res)
				uni.hideLoading();
				console.log(res)
				if (res.statusCode && ( res.statusCode < 200 ||res.statusCode>=300)) {
					uni.showToast({
						title: res.data.message,
						icon: "none",
						duration: 2000
					})
					reject(res.data.msg);
				}
				resolve(res)
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showToast({
					title: "网络异常，请稍后再试!",
					icon: "none",
				})
				reject("网络异常，请稍后再试!");
			},
			complete: () => {}
		}

		options = {
			...options,
			...obj
		};
		// 确保 data 是 JSON 字符串
		if (options.method === "POST") {
			options.data = JSON.stringify(options.data);
		}
		console.log("调用时请求参数是", options.data)

		// 发送请求
		uni.request(options);

	})

}

	// 自定义函数将参数对象转换为查询字符串
	function objectToQueryString(data) {
		return Object.keys(data)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
			.join('&');
	}

export default {
	GET(url, data = {}, config) {
		// 检查 URL 是否包含参数（例如：user/1）
		if (url.includes("$")) {
			// 替换 URL 中的占位符
			url = url.replace(/:[a-zA-Z0-9_]+/g, (placeholder) => {
				const key = placeholder.slice(1); // 去掉冒号
				return data[key] || placeholder; // 如果 data 中有对应的值，则替换，否则保留占位符
			});
			// 删除已处理的路径参数
			for (const key of Object.keys(data)) {
				if (url.includes(key)) {
					delete data[key];
				}
			}
		}
		return HTTP({
			url,
			data,
			method: "GET"
		}, config);
	},

	POST(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "POST"
		}, config);
	},
	PUT(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "PUT"
		}, config);
	},
	DELETE(url, data = {}, config) {
		// 将参数拼接在 URL 上
		if (Object.keys(data).length > 0) {
			url += "?" + objectToQueryString(data);
		}
		return HTTP({
			url,
			data,
			method: "DELETE"
		}, config);
	},

	POSTformdata(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "POST"
		}, config);
	}
	

}